<template>
  <div class="Row_content">
    <Form ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="120">
      <FormItem label="支付通道类型:"
        prop="payPassageType">
        <Select v-model="formValidate.payPassageType"
          style="width:280px"
          @on-change="passageTypeChange">
          <Option v-for="item in payPassageTypeLists"
            :value="item.value"
            :key="item.value">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="支付服务商:"
        v-if="serviceNameShow"
        prop="payService">
        <Select v-model="formValidate.payService"
          style="width:280px"
          @on-change="serviceChange">
          <Option v-for="item in serviceNames"
            :value="item.value"
            :key="item.value">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="支付方式:"
        prop="payWay">
        <Select v-model="formValidate.payWay"
          style="width:280px">
          <Option v-for="item in payways"
            :value="item.value"
            :key="item.value">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="通道费率:"
        prop="passagePercentage">
        <Input v-model="formValidate.passagePercentage"
          placeholder="请输入"
          @on-keyup="rateChange"
          class="Row_content_input">
          <span slot="append">%</span>
        </Input>
      </FormItem>
      <FormItem label="备注:"
        prop="remark">
        <Input v-model="formValidate.remark"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          :maxlength="100"
          placeholder="请描述"
          @on-keyup="filterSpace"
          class="Row_content_input"></Input>
        <span class="rol_tipsd">
          {{ formValidate.remark.length }}/100
        </span>
      </FormItem>
      <FormItem class="form-btn"
        style="margin-top: 5px;">
        <Button type="primary"
          class="system-submit-btn"
          @click="handleSubmit">确定</Button>
        <Button class="system-submit-btn"
          @click="handleReset"
          style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import payPassageMixins from '../mixins/payPassage'
import { addPassageway, updatePassageway, getPassagewayDetail } from '@/api/pay/passageway.js'
import { getServiceSelects } from '@/api/pay/service.js'
export default {
  name: 'payment_passageway_edit',
  mixins: [payPassageMixins],
  data () {
    const checkNum = (rule, value, callback) => {
      if (/[a-zA-Z]/.test(value)) {
        callback(new Error('请输入正确的费率'))
      }
      callback()
    }
    return {
      formValidate: {
        payService: '',
        payPassageType: '',
        payWay: '',
        passagePercentage: '',
        remark: ''
      },
      serviceNames: [],
      payways: [],
      serviceNameShow: true,
      gettingDetail: false,
      ruleValidate: {
        payService: [{ required: true, message: '支付服务商不能为空' }],
        payWay: [{ required: true, message: '支付方式不能为空' }],
        payPassageType: [{ required: true, message: '支付通道类型不能为空' }],
        passagePercentage: [{ validator: checkNum, trigger: 'blur' }]
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.id !== to.params.id) {
        vm.id = to.params.id
        vm.getDetail()
      }
    })
  },
  mounted () {
    this.getServiceLists()
    this.id = this.$route.params.id
    this.getDetail()
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  methods: {
    filterSpace () {
      this.formValidate.remark = this.formValidate.remark.replace(/\s+/g, '')
    },
    getServiceLists () {
      getServiceSelects({
        merchantId: this.merchantId,
        deleted: 0
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          const payServices = result.data || []
          let obj = {}
          payServices.forEach(item => {
            obj[item.providerName] = item.providerCode
          })
          this.payPassageTypeLists.forEach(item => {
            (item.children || []).forEach(val => {
              val.value = obj[val.label]
            })
          })
        }
      })
    },
    getDetail () {
      if (this.id) {
        this.gettingDetail = true
        getPassagewayDetail({
          merchantId: this.merchantId,
          paymentChannelId: this.id
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            const form = result.data || {}
            this.formValidate = {
              payService: form.providerCode,
              payPassageType: form.channelType + '',
              payWay: form.channelCode + '',
              passagePercentage: form.rate || '',
              remark: form.remark
            }
            this.passageTypeChange(this.formValidate.payPassageType)
            this.serviceChange(this.formValidate.payService)
            this.$nextTick(() => {
              this.gettingDetail = false
            })
          } else {
            this.gettingDetail = false
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.gettingDetail = false
          this.$Message.error(`${err}`)
        })
      }
    },
    passageTypeChange (val) {
      const copyList = { ...this.formValidate }
      if (!this.gettingDetail) {
        this.$refs.formValidate.resetFields()
        this.formValidate = {
          payService: '',
          payWay: '',
          payPassageType: copyList.payPassageType,
          passagePercentage: copyList.passagePercentage,
          remark: copyList.remark
        }
        this.serviceNames = []
        this.payways = []
      }
      this.payPassageTypeLists.forEach(item => {
        if (item.value === val) {
          this.serviceNames = item.children.filter(child => child.value)
          if (item.value === '7' || item.value === '8' || item.value === '10') {
            this.serviceNameShow = false
            this.payways = item.children[0].children
          } else {
            this.serviceNameShow = true
          }
        }
      })
    },
    serviceChange (val) {
      const copyList = { ...this.formValidate }
      this.serviceNames.forEach(item => {
        if (item.value === val && item.value) {
          if (!this.gettingDetail) {
            this.$refs.formValidate.resetFields()
            this.formValidate = {
              payService: copyList.payService,
              payWay: '',
              payPassageType: copyList.payPassageType,
              passagePercentage: copyList.passagePercentage,
              remark: copyList.remark
            }
          }
          this.payways = item.children
        }
      })
    },
    rateChange () {
      const formValidate = this.formValidate
      formValidate.passagePercentage = formValidate.passagePercentage.replace(/[^0-9.]/g, '')
      const rate = formValidate.passagePercentage
      const splits = rate.split('.')
      if (splits.length > 2) {
        formValidate.passagePercentage = [splits[0], splits[1]].join('.')
      } else if (splits.length > 1 && splits[1].length > 2) {
        formValidate.passagePercentage = [splits[0], splits[1].substring(0, 2)].join('.')
      }
      if (rate > 100) {
        formValidate.passagePercentage = formValidate.passagePercentage.substring(0, 2)
      }
    },
    handleSubmit () {
      this.$refs.formValidate.validate(val => {
        if (val) {
          const formValidate = this.formValidate
          const params = {
            channelType: +formValidate.payPassageType,
            channelCode: +formValidate.payWay,
            remark: formValidate.remark,
            merchantId: this.merchantId,
            providerCode: formValidate.payService,
            rate: formValidate.passagePercentage ? +formValidate.passagePercentage : ''
          }
          let request
          if (this.id) {
            request = updatePassageway({ ...params, paymentChannelId: this.id })
          } else {
            request = addPassageway(params)
          }
          request.then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success(this.id ? '编辑成功！' : '新增成功！')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'payment_passageway_list'
        })
      })
    }
  }
}
</script>

<style lang="less">
.rol_tipsd {
  display: inline-block;
  width: 100%;
  text-align: right;
  font-size: 12px;
  line-height: 14px;
  color: #c5c8ce;
}
</style>
